//
//  CartoonMyDownLoadAlreadyViewController.m
//  Cartoon
//
//  Created by dllo on 15/11/6.
//  Copyright © 2015年 YSZ. All rights reserved.
//

#import "CartoonMyDownLoadAlreadyViewController.h"
#import "CartoonMyDownLoad.h"
#import "CartoonReadingViewController.h"

@interface CartoonMyDownLoadAlreadyViewController ()
@property (nonatomic, strong) UIScrollView *scrollerView;
@property (nonatomic, strong) NSMutableDictionary *dataDic;
@property (nonatomic, strong) NSMutableArray *deleteArr;
@end

@implementation CartoonMyDownLoadAlreadyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self handler];

}
- (void)handler
{
    self.dataDic = [NSMutableDictionary dictionary];
    self.deleteArr = [NSMutableArray array];
    
    BOOL isOpen = [[FMDB shareFMDB].db open];
    if (!isOpen) {
        NSLog(@"打开失败");
    }else{
        
        BOOL creatResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"create table CartoonMyDownLoad (name text , image text , cartoonID text primary key , cartoonPage text)"]];
        NSLog(@"创建是否成功 : %d",creatResult);
    }
    
    FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM CartoonMyDownLoad"];
    self.pageArray = [NSMutableArray array];
    
    while ([set next]) {
        CartoonMyDownLoad *down = [[CartoonMyDownLoad alloc]init];
        down.name = [set stringForColumn:@"name"];
        down.cartoonID = [set stringForColumn:@"cartoonID"];
        down.cartoonPage = [set stringForColumn:@"cartoonPage"];
        down.image = [set stringForColumn:@"image"];
        if ([[[down.cartoonID componentsSeparatedByString:@"/"] lastObject] isEqualToString:self.comic_id]) {
            [self.pageArray addObject:[NSString stringWithFormat:@"%ld",[down.cartoonPage integerValue]]];
            [self.dataDic setObject:down forKey:down.cartoonPage];
        }
    }

    
    for (NSInteger i = 0; i < _pageArray.count; i++) {
        NSInteger min = i;
        for (NSInteger j = i; j < _pageArray.count - 1; j++) {
            if ([self.pageArray[min] integerValue] > [self.pageArray[j + 1] integerValue]) {
                min = j + 1;
            }
        }
        if (min != i) {
            NSString *temp = [NSString stringWithString:self.pageArray[i]];
            self.pageArray[i] = [NSString stringWithString:self.pageArray[min]];
            self.pageArray[min] = [NSString stringWithString:temp];
        }
    }
    
    NSMutableArray *countArr = [NSMutableArray array];
    for (NSInteger i = 0; i < _pageArray.count; i++) {
    CartoonMyDownLoad *down = [self.dataDic objectForKey:_pageArray[i]];
    NSString *strr = [NSString stringWithFormat:@"%@%@",[[down.cartoonID componentsSeparatedByString:@"/"] firstObject],[[down.cartoonID componentsSeparatedByString:@"/"] lastObject]];
//    NSLog(@"%@",strr);
    //初始化Documents路径
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
    //初始化临时文件路径
    NSString *folderPath = [path stringByAppendingPathComponent:strr];
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断temp文件夹是否存在
    
    //    NSLog(@"%@",myPath);
    NSArray *arr = [fileManager directoryContentsAtPath:folderPath];
        NSMutableArray *array = [NSMutableArray array];
        for (NSString *str in arr) {
            if ([[[str componentsSeparatedByString:@"."] lastObject] isEqualToString:@"jpg"]) {
                [array addObject:str];
            }
        }
        if (array.count > 0) {
            
        }else{
            [countArr addObject:_pageArray[i]];
        }
        
    
    }
    for (NSString *str in countArr) {
        [_pageArray removeObject:str];
    }
    UILabel *label = [[UILabel alloc] initWithFrame:self.view.bounds];
    label.text = @"您还没有下载章节哦";
    label.textAlignment = NSTextAlignmentCenter;
    label.tag = 101;
    label.hidden = YES;
    label.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:label];
    
    NSLog(@"arrraraaaararar%ld",_pageArray.count);
    if (_pageArray.count == 0) {
        label.hidden = NO;
    }
    self.scrollerView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, SelfViewWidth, SelfViewHeight - 64 - 49)];
    
    for (NSInteger i = 0; i < _pageArray.count; i++) {NSLog(@"123123123");
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        if (i % 3 == 0) {
            button.frame = CGRectMake(10, 50 * (i / 3 + 0.3), SelfViewWidth / 3 - 20, 40);
            
        }else if (i % 3 == 1){
            button.frame = CGRectMake(SelfViewWidth / 3 - 20 + 10 + 20, 50 * (i / 3 + 0.3), SelfViewWidth / 3 - 20, 40);
        }else{
            button.frame = CGRectMake((SelfViewWidth / 3 - 20) * 2 + 10 + 20 + 20, 50 * (i / 3 + 0.3), SelfViewWidth / 3 - 20, 40);
        }

        
         
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        self.scrollerView.contentSize = CGSizeMake(0, button.frame.origin.y + 40 + 20);
        button.tag = [_pageArray[i] integerValue];
        [button setTitle:_pageArray[i] forState:UIControlStateNormal];
        button.titleLabel.text = _pageArray[i];
        button.layer.borderWidth = 1;
        [_scrollerView addSubview:button];
            
        
    }
    
    UIButton *allChangeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    allChangeButton.frame = CGRectMake(0, SelfViewHeight - 64 - 49, SelfViewWidth / 2, 49);
    [allChangeButton setTitle:@"全选" forState:UIControlStateNormal];
    allChangeButton.titleLabel.text = @"全选";
    [allChangeButton addTarget:self action:@selector(allChangeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    allChangeButton.layer.borderWidth = 1;
    allChangeButton.tag = 1001;
    allChangeButton.hidden = YES;
    [self.view addSubview:allChangeButton];
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    cancelButton.frame = CGRectMake(SelfViewWidth / 2, SelfViewHeight - 64 - 49, SelfViewWidth / 2, 49);
    [cancelButton setTitle:@"删除" forState:UIControlStateNormal];
    cancelButton.titleLabel.text = @"删除";
    [cancelButton addTarget:self action:@selector(cancelButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    cancelButton.layer.borderWidth = 1;
    cancelButton.tag = 1002;
    cancelButton.hidden = YES;
    [self.view addSubview:cancelButton];
    
    [self.view addSubview:_scrollerView];
    [self.view sendSubviewToBack:_scrollerView];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemAction:)];
}
- (void)allChangeButtonAction:(UIButton *)btn
{
    if ([btn.titleLabel.text isEqualToString:@"全选"]) {
        UIButton *button1 = (UIButton *)[self.view viewWithTag:1001];
        [button1 setTitle:@"全选" forState:UIControlStateNormal];
        button1.titleLabel.text = @"全选";
        [self.deleteArr removeAllObjects];
        for (NSString *str in _pageArray) {
            UIButton *button = (UIButton *)[self.scrollerView viewWithTag:[str integerValue]];
            button.backgroundColor = [UIColor redColor];
            [self.deleteArr addObject:button];
        }
    }else{
        UIButton *button1 = (UIButton *)[self.view viewWithTag:1001];
        [button1 setTitle:@"取消全选" forState:UIControlStateNormal];
        button1.titleLabel.text = @"取消全选";
        [self.deleteArr removeAllObjects];
        for (NSString *str in _pageArray) {
            UIButton *button = (UIButton *)[self.scrollerView viewWithTag:[str integerValue]];
            button.backgroundColor = nil;
        }
    }

}
- (void)cancelButtonAction:(UIButton *)btn
{
    
    for (UIButton *btn in _deleteArr) {
        
        [btn removeFromSuperview];
    
    CartoonMyDownLoad *down = [self.dataDic objectForKey:btn.titleLabel.text];
    NSString *strr = [NSString stringWithFormat:@"%@%@",[[down.cartoonID componentsSeparatedByString:@"/"] firstObject],[[down.cartoonID componentsSeparatedByString:@"/"] lastObject]];
    NSLog(@"%@",strr);
    //初始化Documents路径
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
    //初始化临时文件路径
    NSString *folderPath = [path stringByAppendingPathComponent:strr];
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断temp文件夹是否存在
    
        NSLog(@"%@",folderPath);
    [fileManager removeItemAtPath:folderPath error:nil];
        
      
        
        BOOL isOpen = [[FMDB shareFMDB].db open];
        
        if (!isOpen) {
            NSLog(@"打开失败");
        }else{
           
        }
        
    [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"delete from CartoonMyDownLoad where cartoonID = '%@'",down.cartoonID]];
    }
}
- (void)rightBarButtonItemAction:(UIBarButtonItem *)item
{
    if ([item.title isEqualToString:@"编辑"]) {
        item.title = @"取消";
        UIButton *button1 = (UIButton *)[self.view viewWithTag:1001];
        button1.hidden = NO;
        UIButton *button2 = (UIButton *)[self.view viewWithTag:1002];
        button2.hidden = NO;
        for (NSString *str in _pageArray) {
            UIButton *button = (UIButton *)[self.scrollerView viewWithTag:[str integerValue]];
            [button removeTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            [button addTarget:self action:@selector(deleteButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        }
    }else{
        item.title = @"编辑";
        UIButton *button1 = (UIButton *)[self.view viewWithTag:1001];
        button1.hidden = YES;
        UIButton *button2 = (UIButton *)[self.view viewWithTag:1002];
        button2.hidden = YES;
        for (NSString *str in _pageArray) {
            UIButton *button = (UIButton *)[self.scrollerView viewWithTag:[str integerValue]];
            [button removeTarget:self action:@selector(deleteButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            button.backgroundColor = nil;
        }
    }
}
- (void)deleteButtonAction:(UIButton *)btn
{
    if (btn.backgroundColor == nil) {
        btn.backgroundColor = [UIColor redColor];
        [self.deleteArr addObject:btn];
    }else{
        btn.backgroundColor = nil;
        [self.deleteArr removeObject:btn];
    }
    
}
- (void)buttonAction:(UIButton *)btn
{
    
    CartoonReadingViewController *reading = [[CartoonReadingViewController alloc] init];
    
    CartoonMyDownLoad *down = [self.dataDic objectForKey:btn.titleLabel.text];
    NSString *strr = [NSString stringWithFormat:@"%@%@",[[down.cartoonID componentsSeparatedByString:@"/"] firstObject],[[down.cartoonID componentsSeparatedByString:@"/"] lastObject]];
    NSLog(@"%@",strr);
    //初始化Documents路径
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
    //初始化临时文件路径
    NSString *folderPath = [path stringByAppendingPathComponent:strr];
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断temp文件夹是否存在
    BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
    if (!fileExists) {//如果不存在说创建,因为下载时,不会自动创建文件夹
        [fileManager createDirectoryAtPath:folderPath
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
    }
    //    NSLog(@"%@",myPath);
    NSArray *arr = [fileManager directoryContentsAtPath:folderPath];
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *str in arr) {
        if ([[[str componentsSeparatedByString:@"."] lastObject] isEqualToString:@"jpg"]) {
            [array addObject:str];
        }
    }
    
//    reading.myTitle = [[self.pictureDicArr objectAtIndex:indexPath.row] objectForKey:@"title"];
    
    reading.filePictureArray = [NSArray arrayWithArray:array];
    NSLog(@"%@",_pageArray);
    reading.path = folderPath;
    reading.pageArray = _pageArray;
    reading.page = [btn.titleLabel.text integerValue];
    reading.dataDic = self.dataDic;
    [self.navigationController pushViewController:reading animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
